package com.youcheng.utils;

import org.springframework.util.DigestUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Helper {

    /**
     * 创建管理员token
     * @param username
     * @return
     */
    public static String createAdminToken(String username){
        Integer timeSecond = getTimeSecond();
        String newString = username+Integer.toString(timeSecond);
        return DigestUtils.md5DigestAsHex(newString.getBytes());
    }

    /**
     *
     * @param format
     * @return
     */
    public static String getCurrentDate(String format){
        if(format == null || format.isEmpty()){
            format = "yyyy-MM-dd HH:mm:ss";
        }
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(d);
    }

    /**
     *
     * @return
     */
    public static Integer getTimeSecond(){
        Date date = new Date();
        long time = date.getTime();
        String timestamp = String.valueOf(time/1000);
        return Integer.valueOf(timestamp);
    }

    /**
     *
     * @param str
     * @param format
     * @return
     */
    public static String timestamp2Date(Long str,String format ) {
        //yyyy-mm-dd HH:mm:ss
        String str_num = Long.toString(str);
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        if (str_num.length() == 13) {
            String date = sdf.format(new Date(Long.parseLong(str_num)));
            return date;
        } else {
            String date = sdf.format(new Date(Integer.parseInt(str_num) * 1000L));
            return date;
        }
    }

    public static String timestamp2Date(int str,String format ) {
        //yyyy-mm-dd HH:mm:ss
        String str_num = Integer.toString(str);
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        if (str_num.length() == 13) {
            String date = sdf.format(new Date(Long.parseLong(str_num)));
            return date;
        } else {
            String date = sdf.format(new Date(Integer.parseInt(str_num) * 1000L));
            return date;
        }
    }

}
